import { createRouter, createWebHistory } from 'vue-router'

// 路由懒加载
const Login = () => import('@/views/auth/Login.vue')
const Register = () => import('@/views/auth/Register.vue')
const Dashboard = () => import('@/views/dashboard/Dashboard.vue')
const NotFound = () => import('@/views/error/NotFound.vue')

// 工单相关页面
const WorkOrderList = () => import('@/views/workorder/WorkOrderList.vue')
const WorkOrderDetail = () => import('@/views/workorder/WorkOrderDetail.vue')
const WorkOrderCreate = () => import('@/views/workorder/WorkOrderCreate.vue')
const WorkOrderEdit = () => import('@/views/workorder/WorkOrderEdit.vue')

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresAuth: false }
  },
  {
    path: '/register',
    name: 'Register',
    component: Register,
    meta: { requiresAuth: false }
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: Dashboard,
    meta: { requiresAuth: true }
  },
  {
    path: '/workorder',
    name: 'WorkOrderList',
    component: WorkOrderList,
    meta: { requiresAuth: true }
  },
  {
    path: '/workorder/create',
    name: 'WorkOrderCreate',
    component: WorkOrderCreate,
    meta: { requiresAuth: true }
  },
  {
    path: '/workorder/:id',
    name: 'WorkOrderDetail',
    component: WorkOrderDetail,
    meta: { requiresAuth: true }
  },
  {
    path: '/workorder/edit/:id',
    name: 'WorkOrderEdit',
    component: WorkOrderEdit,
    meta: { requiresAuth: true }
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: NotFound
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 全局导航守卫
router.beforeEach((to, from, next) => {
  console.log('路由守卫检查:', to.path)
  // 检查路由是否需要认证
  if (to.matched.some(record => record.meta.requiresAuth)) {
    const userStr = localStorage.getItem('user')
    console.log('用户信息:', userStr)
    
    if (!userStr) {
      console.log('未找到用户信息，重定向到登录页')
      // 如果没有用户信息，重定向到登录页
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      try {
        const user = JSON.parse(userStr)
        if (user && user.username) {
          console.log('用户已登录:', user.username)
          next() // 如果有用户信息，正常导航
        } else {
          console.log('用户信息无效，重定向到登录页')
          next({
            path: '/login',
            query: { redirect: to.fullPath }
          })
        }
      } catch (e) {
        console.error('解析用户信息出错:', e)
        next({
          path: '/login',
          query: { redirect: to.fullPath }
        })
      }
    }
  } else {
    next() // 不需要认证的路由，正常导航
  }
})

export default router 
 